import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import 'package:wallpaper/components/AlertDialog/my_loading.dart';
import 'package:wallpaper/components/placeholder/empty.dart';
import 'package:wallpaper/components/images/image_load.dart';
import 'package:wallpaper/model/options_base.dart';
import 'package:wallpaper/components/video/video_page_view.dart';
import 'package:wallpaper/providers/setting_provider.dart';
import 'package:wallpaper/tools/route_animation.dart';
import 'dart:async';

class VideoList extends StatefulWidget {
  final List videoList;
  final bool isLoading;
  final Function onImageBottomLoading;
  final Function onImageListRefresh;
  final bool isPC;
  const VideoList({
    super.key,
    required this.videoList,
    required this.isLoading,
    required this.onImageBottomLoading,
    required this.onImageListRefresh,
    this.isPC = false,
  });

  @override
  State<VideoList> createState() => _ImageListState();
}

class _ImageListState extends State<VideoList> {
  // 用于取消延时器
  Timer? _refreshTimer;
  // 用于跟踪刷新操作
  Completer<void>? _refreshCompleter;
  // 用于跟踪滚动到底部加载操作的计时器
  Timer? _loadMoreTimer;
  // 标记是否正在执行加载操作
  bool _isLoadingMore = false;

  @override
  void initState() {
    super.initState();
    _refreshTimer = null;
    _refreshCompleter = null;
    _loadMoreTimer = null;
  }

  @override
  void dispose() {
    // 取消定时器
    _refreshTimer?.cancel();
    _loadMoreTimer?.cancel();

    // 确保在组件销毁时完成任何未完成的刷新操作
    if (_refreshCompleter != null && !_refreshCompleter!.isCompleted) {
      _refreshCompleter!.complete();
    }

    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return RefreshIndicator(
        child: NotificationListener<ScrollNotification>(
          // 使用NotificationListener监听滚动事件
          onNotification: (ScrollNotification scrollInfo) {
            double bottomDistance =
                scrollInfo.metrics.maxScrollExtent - scrollInfo.metrics.pixels;
            if (scrollInfo is ScrollUpdateNotification &&
                bottomDistance <= 400) {
              if (widget.isLoading || _isLoadingMore) return false;

              // 立即触发加载
              _isLoadingMore = true;
              widget.onImageBottomLoading();

              // 设置计时器，在1秒后允许再次触发加载
              _loadMoreTimer?.cancel();
              _loadMoreTimer = Timer(Duration(milliseconds: 1000), () {
                if (mounted) {
                  _isLoadingMore = false;
                }
              });
            }
            // 监听滚动停止
            if (scrollInfo is ScrollEndNotification) {}
            return false; // 返回false以允许事件继续冒泡
          },
          child: RepaintBoundary(
            child: _buildShowBody(),
          ),
        ),
        onRefresh: () {
          // 取消现有的定时器（如果有）
          _refreshTimer?.cancel();

          // 创建新的 Completer 来处理刷新操作
          _refreshCompleter = Completer<void>();

          // 执行刷新操作
          widget.onImageListRefresh();

          // 设置延时自动完成刷新
          _refreshTimer =
              Timer(Duration(milliseconds: OptionsBase().refreshTime), () {
            // 检查 Completer 是否仍然有效且未完成
            if (_refreshCompleter != null && !_refreshCompleter!.isCompleted) {
              _refreshCompleter!.complete();
            }
          });

          // 返回 Completer 的 future
          return _refreshCompleter!.future;
        });
  }

  Widget _buildShowBody() {
    final SettingProvider setting = Provider.of<SettingProvider>(context);
    final theme = Theme.of(context).colorScheme;

    if (widget.isLoading && widget.videoList.isEmpty) {
      return const Center(
        child: CircularProgressIndicator(),
      );
    } else if (widget.videoList.isEmpty) {
      return Empty();
    } else {
      return CustomScrollView(
        physics: const BouncingScrollPhysics(
          parent: AlwaysScrollableScrollPhysics(),
        ),
        cacheExtent: 200,
        slivers: [
          SliverToBoxAdapter(
            child: Container(
              height: MediaQuery.of(context).padding.top,
              color: Theme.of(context).colorScheme.primaryContainer,
            ),
          ),
          SliverPadding(
            padding: EdgeInsets.all(setting.padding),
            sliver: SliverGrid(
              gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
                crossAxisCount: widget.isPC
                    ? OptionsBase().horizontalColumns(context)
                    : OptionsBase().imageColumns(context),
                childAspectRatio: widget.isPC ? 1.7 : 0.7,
                mainAxisSpacing: setting.padding,
                crossAxisSpacing: setting.padding,
              ),
              delegate: SliverChildBuilderDelegate(
                (context, index) {
                  return buildItem(context, index, setting.radius, theme);
                },
                childCount: widget.videoList.length,
              ),
            ),
          ),
          SliverToBoxAdapter(
            child: Padding(
              padding: const EdgeInsets.all(3.0),
              child: SizedBox(
                height: 30,
                child: Center(
                  child: widget.isLoading
                      ? MyLoading(
                          type: 1,
                          size: 30,
                        )
                      : Text(
                          '~ 已经到底了 ~',
                          style: TextStyle(
                            color: theme.onSurface.withAlpha(90),
                          ),
                        ),
                ),
              ),
            ),
          )
        ],
      );
    }
  }

  Widget buildItem(context, int index, double radius, ColorScheme theme) {
    return Container(
      decoration: BoxDecoration(
          color: theme.surface,
          borderRadius: BorderRadius.circular(radius),
          boxShadow: [
            BoxShadow(
              color: theme.shadow,
              offset: Offset(1, 2),
              blurRadius: 2,
            ),
          ]),
      child: ClipRRect(
          borderRadius: BorderRadius.circular(radius),
          child: Stack(
            alignment: Alignment.bottomLeft,
            children: [
              SizedBox(
                  width: double.infinity,
                  height: double.infinity,
                  child: ImageLoad(imageUrl: widget.videoList[index].cover)),
              Center(
                child: Icon(
                  Icons.play_circle,
                  color: const Color.fromARGB(173, 255, 255, 255),
                  size: 50,
                ),
              ),
              if (widget.videoList[index].tag != "")
                Container(
                    width: double.infinity,
                    padding: EdgeInsets.all(3),
                    decoration: BoxDecoration(
                      gradient: LinearGradient(
                        begin: Alignment.topCenter,
                        end: Alignment.bottomCenter,
                        colors: [
                          Colors.black.withOpacity(0),
                          Colors.black.withOpacity(1),
                        ],
                      ),
                    ),
                    child: Text(
                      widget.videoList[index].tag,
                      overflow: TextOverflow.ellipsis,
                      maxLines: 1,
                      style: TextStyle(color: Colors.white, fontSize: 13),
                    )),
              Positioned.fill(
                child: Material(
                  color: Colors.transparent,
                  child: InkWell(
                    onTap: () {
                      RouteAnimation().animateRoute(
                        context,
                        VideoPageView(
                          videoList: widget.videoList,
                          activeIndex: index,
                          resetGetdata: () {},
                        ),
                      );
                    },
                  ),
                ),
              ),
            ],
          )),
    );
  }
}
